package com.mh.rpc.consumer.proxy;

import com.alibaba.fastjson.JSON;
import com.mh.rpc.api.common.RpcRequest;
import com.mh.rpc.api.common.RpcResponse;
import com.mh.rpc.consumer.client.RpcClient;
import com.mh.rpc.consumer.loadbalance.RoundRobin;
import com.mh.rpc.consumer.loadbalance.ServerInfo;

import java.lang.reflect.Proxy;
import java.util.UUID;

public class RpcClientProxy {

    private static final RoundRobin ROUND_ROBIN = new RoundRobin();

    public static Object createProxy(Class<?> serviceClass) {
        return Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(),
                new Class[]{serviceClass},
                (proxy, method, args) -> {
                    RpcRequest rpcRequest = new RpcRequest();
                    rpcRequest.setRequestId(UUID.randomUUID().toString());
                    rpcRequest.setClassName(method.getDeclaringClass().getName());
                    rpcRequest.setMethodName(method.getName());
                    rpcRequest.setParameters(args);
                    rpcRequest.setParameterTypes(method.getParameterTypes());
                    ServerInfo server = ROUND_ROBIN.getServer();
                    RpcClient rpcClient = new RpcClient(server.getHost(), server.getPort());
                    try {
                        Object responseMsg = rpcClient.send(JSON.toJSONString(rpcRequest));
                        RpcResponse rpcResponse = JSON.parseObject(responseMsg.toString(), RpcResponse.class);
                        if (rpcResponse.getError() != null) {
                            throw new RuntimeException(rpcResponse.getError());
                        }
                        Object result = rpcResponse.getResult();
                        return JSON.parseObject(result.toString(), method.getReturnType());
                    } catch (Exception e) {
                        e.printStackTrace();
                    } finally {
                        rpcClient.close();
                    }
                    return null;
                }
        );
    }

}
